var axios = require('axios');
var token = ''
module.exports = {
  schedule: {
    interval: '2s', // 1 s间隔
    type: 'all', // 指定所有的 worker 都需要执行
  },
  async task(ctx) {

    try {
      const data = await ctx.model.Device.find({})
        .sort({ _Timestamp: -1 })
        .limit(20)
      // 计算平均值
      if (data.length === 0) {
        return 0;
      }
      let sum = data.reduce((acc, item) => acc + item.wz_velocity, 0) / data.length;
      console.log('====0', sum)

      let a = 8000;
      let b = 0;
      if (sum < 0.7) {
        b = (Math.floor(Math.random() * (0.987223 - 0.94562343 + 1)) + 0.94562343)
        rlife = a * b
        console.log('==========111', rlife, b)
      } else if (sum < 4.5) {
        b = (Math.floor(Math.random() * (0.723434 - 0.545223 + 1)) + 0.545223)
        rlife = a * b
        console.log('==========222', rlife, b)
      } else if (sum < 8) {
        b = (Math.floor(Math.random() * (0.48202323 - 0.230823 + 1)) + 0.230823)
        rlife = a * b
        console.log('==========333', rlife, b)
      } else if (sum < 12) {
        b = (Math.floor(Math.random() * (0.22298324 - 0.153223 + 1)) + 0.153223)
        rlife = a * b
        console.log('==========444', rlife, b)
      } else {
        b = (Math.floor(Math.random() * (0.1111232323 - 0.0793243434 + 1)) + 0.0793243434)
        rlife = a * b
      }

      if (rlife < a) {
        ctx.app.rlife = rlife
      }
      // 发送到根云积木

      // if (rlife < a) {
      //   axios.post('https://nocode.rootcloud.com/api/workflow/hooks/NjcxNjYwNTVjNjFmNzQ0MTFhYzU4MzM4', {
      //     rlife
      //   }).then(res => {
      //     // console.log(res)
      //   })
      // }

    } catch (error) {
      console.error(error);
      return 0;
    }
  },
};